package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.Exchanger;

@Service
@Slf4j
public class ExchangerExampleService {

    // 只适用于两个线程之间交换数据
    private final Exchanger<String> exchanger = new Exchanger<>();

    public void executeExchangerTask() {
        new Thread(() -> {
            try {
                String data = "来自线程 1 的数据";
                log.info("线程 1 正在交换数据: {}", data);
                String exchangedData = exchanger.exchange(data);
                log.info("线程 1 接收到交换的数据: {}", exchangedData);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();

        new Thread(() -> {
            try {
                String data = "来自线程 2 的数据";
                log.info("线程 2 正在交换数据: {}", data);
                String exchangedData = exchanger.exchange(data);
                log.info("线程 2 接收到交换的数据: {}", exchangedData);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }
}
